<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useSnackbarStore } from '@/store/snackbarStore';
import { getApprovedInitialAppointments, createVisitRecord, updateAppointmentStatus } from '@/api/initialVisitor';

interface IAppointment {
  id: number;
  student_id: number;
  student_username: string;
  student_name: string;
  student_phone: string;
  type: string;
  duty_id: number;
  status: string;
  apply_time: string;
  approve_time: string;
  reviewer_id: number;
  scheduled_time: string;
  scheduled_place: string;
  cancel_reason: string;
  is_urgent: boolean;
}

interface IVisitRecord {
  appointment_id: number;
  visitor_id: number;
  type: string;
  visit_time: string;
  risk_level: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
  problem_type: string;
  conclusion: '无需咨询' | '建议心理咨询';
  note: string;
}

const itemsPerPage = ref(10);
const appointments = ref<IAppointment[]>([]);
const loading = ref(true);
const snackbarStore = useSnackbarStore();

// 录入对话框相关
const recordDialog = ref(false);
const selectedAppointment = ref<IAppointment | null>(null);
const recordForm = reactive<IVisitRecord>({
  appointment_id: 0,
  visitor_id: 1, // 默认初访员ID，实际应该从登录用户获取
  type: 'INITIAL',
  visit_time: '',
  risk_level: 'LOW',
  problem_type: '',
  conclusion: '无需咨询',
  note: ''
});

// 表格列定义
const headers = reactive([
  { title: '学号', key: 'student_username', width: '100px' },
  { title: '申请时间', key: 'apply_time', width: '150px' },
  { title: '预约时间', key: 'scheduled_time', width: '150px' },
  { title: '预约地点', key: 'scheduled_place', width: '200px' },
  { title: '操作', key: 'action', sortable: false, width: '100px' }
]);

// 危机等级选项
const riskLevelOptions = [
  { title: '低', value: 'LOW' },
  { title: '中', value: 'MEDIUM' },
  { title: '高', value: 'HIGH' },
  { title: '严重', value: 'CRITICAL' }
];

// 初访结论选项
const conclusionOptions = [
  { title: '无需咨询', value: '无需咨询' },
  { title: '建议心理咨询', value: '建议心理咨询' }
];

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '';
  return new Date(dateTime).toLocaleString('zh-CN');
};

// 加载已批准的初访预约数据
const loadApprovedAppointments = async () => {
  loading.value = true;
  try {
    const response = await getApprovedInitialAppointments();
    console.log('获取已批准初访预约响应:', response);
    
    if (response.data && response.data.code === 200 && response.data.data) {
      appointments.value = response.data.data;
    } else {
      console.error('Invalid response format:', response);
      appointments.value = [];
    }
  } catch (error) {
    console.error('Error loading appointments:', error);
    snackbarStore.showMessage('加载预约数据失败');
    appointments.value = [];
  } finally {
    loading.value = false;
  }
};

// 打开录入对话框
const openRecordDialog = (appointment: IAppointment) => {
  selectedAppointment.value = appointment;
  recordForm.appointment_id = appointment.id;
  recordForm.visit_time = '';
  recordForm.risk_level = 'LOW';
  recordForm.problem_type = '';
  recordForm.conclusion = '无需咨询';
  recordForm.note = '';
  recordDialog.value = true;
};

// 验证表单
const isFormValid = computed(() => {
  return recordForm.visit_time && 
         recordForm.problem_type && 
         recordForm.conclusion && 
         recordForm.note;
});

// 提交初访记录
const submitVisitRecord = async () => {
  if (!isFormValid.value) {
    snackbarStore.showMessage('请填写所有必填项');
    return;
  }

  try {
    console.log('提交初访记录:', recordForm);
    
    // 创建初访记录
    const visitRecordResponse = await createVisitRecord(recordForm);
    console.log('创建初访记录响应:', visitRecordResponse);
    
    if (visitRecordResponse.data && visitRecordResponse.data.code === 200) {
      // 更新预约状态为已完成
      const statusResponse = await updateAppointmentStatus(recordForm.appointment_id, 'COMPLETED');
      console.log('更新预约状态响应:', statusResponse);
      
      snackbarStore.showMessage('初访记录保存成功');
      recordDialog.value = false;
      
      // 重新加载数据
      loadApprovedAppointments();
    } else {
      snackbarStore.showMessage('保存初访记录失败');
    }
  } catch (error) {
    console.error('Error submitting visit record:', error);
    snackbarStore.showMessage('保存初访记录失败');
  }
};

// 刷新数据
const handleRefresh = () => {
  loadApprovedAppointments();
};

// 组件挂载时加载数据
onMounted(() => {
  loadApprovedAppointments();
});
</script>

<template>
  <section>
    <VRow>
      <VCol cols="12">
        <VCard>
          <VCardItem class="py-0">
            <VToolbar tag="div" color="transparent" flat>
              <VToolbarTitle>初访预约管理</VToolbarTitle>
              <VSpacer />
              <VBtn icon @click="handleRefresh" density="comfortable">
                <VIcon>mdi-refresh</VIcon>
                <VTooltip activator="parent">刷新数据</VTooltip>
              </VBtn>
            </VToolbar>
          </VCardItem>
          
          <!-- 数据表格 -->
          <VCardText class="pa-0 pb-5">
            <VDivider />
            <VDataTable
              :headers="headers"
              :items="appointments"
              v-model:items-per-page="itemsPerPage"
              :loading="loading"
              hover
              class="elevation-1"
            >
              <!-- 学号列 -->
              <template #item.student_id="{ item }">
                {{ item.student_id }}
              </template>
              
              <!-- 申请时间列 -->
              <template #item.apply_time="{ item }">
                {{ formatDateTime(item.apply_time) }}
              </template>
              
              <!-- 预约时间列 -->
              <template #item.scheduled_time="{ item }">
                {{ formatDateTime(item.scheduled_time) }}
              </template>
              
              <!-- 预约地点列 -->
              <template #item.scheduled_place="{ item }">
                {{ item.scheduled_place }}
              </template>
              
              <!-- 操作列 -->
              <template #item.action="{ item }">
                <VBtn 
                  size="small"
                  color="primary" 
                  variant="outlined"
                  prepend-icon="mdi-pencil"
                  @click="openRecordDialog(item)"
                >
                  录入
                </VBtn>
              </template>
            </VDataTable>
          </VCardText>
        </VCard>
      </VCol>
    </VRow>

    <!-- 初访信息录入对话框 -->
    <VDialog v-model="recordDialog" max-width="600px">
      <VCard>
        <VCardTitle>初访信息录入</VCardTitle>
        <VCardText>
          <VForm>
            <VRow>
              <VCol cols="12">
                <VSelect
                  label="危机等级"
                  v-model="recordForm.risk_level"
                  :items="riskLevelOptions"
                  :rules="[(v) => !!v || '请选择危机等级']"
                  required
                />
              </VCol>
              <VCol cols="12">
                <VTextField
                  label="问题类型"
                  v-model="recordForm.problem_type"
                  :rules="[(v) => !!v || '请输入问题类型']"
                  required
                />
              </VCol>
              <VCol cols="12">
                <VTextField
                  label="初访时间"
                  v-model="recordForm.visit_time"
                  type="datetime-local"
                  :rules="[(v) => !!v || '请选择初访时间']"
                  required
                />
              </VCol>
              <VCol cols="12">
                <VSelect
                  label="初访结论"
                  v-model="recordForm.conclusion"
                  :items="conclusionOptions"
                  :rules="[(v) => !!v || '请选择初访结论']"
                  required
                />
              </VCol>
              <VCol cols="12">
                <VTextarea
                  label="笔记"
                  v-model="recordForm.note"
                  :rules="[(v) => !!v || '请输入笔记']"
                  rows="4"
                  required
                />
              </VCol>
            </VRow>
          </VForm>
        </VCardText>
        <VCardActions>
          <VSpacer />
          <VBtn 
            color="primary" 
            variant="outlined" 
            @click="submitVisitRecord"
            :disabled="!isFormValid"
          >
            完成
          </VBtn>
          <VBtn color="error" variant="outlined" @click="recordDialog = false">
            取消
          </VBtn>
        </VCardActions>
      </VCard>
    </VDialog>
  </section>
</template>

<style scoped>
.elevation-1 {
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
</style> 